package org.flashbrighton.as3bots.controllers
{
	import de.polygonal.motor2.dynamics.contact.ContactPoint;
	
	import org.flashbrighton.as3bots.bots.BaseBot;
	import org.flashbrighton.as3bots.events.BotEvent;
	import org.flashbrighton.as3bots.models.CollidableType;
	
	public class CollisionScorer
	{
		private var _point:ContactPoint;
		private var _bot1:BaseBot;
		private var _bot2:BaseBot;
		
		
		public function CollisionScorer(point:ContactPoint, bot1:BaseBot, bot2:BaseBot)
		{
			_point = point;
			_bot1 = bot1;
			_bot2 = bot2;
		}
		
		
		public function notifyCollidables():void
		{
			var impulse:Number = _point.Pn / 20000;
			var hitPos1:Number;
			var hitPos2:Number;
			var health1:Number;
			var health2:Number;
			var maxHitScore:int = 100;
			
			// Ignore persistant collisions
			if (impulse < 0.8) maxHitScore = 0;
			
			if (_bot1 == null)
			{
				// Bot has hit a wall.
				hitPos2 = getHitPos(_bot2);
								
				health2 = 0//Math.round(Math.abs(hitPos2) * -maxHitScore * impulse);
				
				_bot2.health.energy += health2;
				_bot2.controller.notify(new BotEvent(BotEvent.HIT, hitPos2, health2, CollidableType.WALL));
				return;
			}
			
			hitPos1 = getHitPos(_bot1);
			hitPos2 = getHitPos(_bot2);
			
			health1 = Math.round(hitPos1 * -maxHitScore * impulse);
			health2 = Math.round(hitPos2 * -maxHitScore * impulse);

			_bot1.health.energy += health1;
			_bot2.health.energy += health2;
			_bot1.controller.notify(new BotEvent(BotEvent.HIT, hitPos1, health1, CollidableType.BOT));			
			_bot2.controller.notify(new BotEvent(BotEvent.HIT, hitPos2, health2, CollidableType.BOT));
 		}
 		
		
		/**
		 * Finds the value based on where a bot gets hit (0 to 1).
		 */
		private function getHitPos(bot:BaseBot):Number
		{
			var botAngle:Number = bot.model.body.r;
			var PI:Number = Math.PI;
			var twoPI:Number = PI * 2;
			
			botAngle += PI;
			botAngle %= twoPI;
			if (botAngle < 0) botAngle += twoPI;
			botAngle -= PI;
			
			var hitAngle:Number = Math.atan2(_point.y - bot.model.body.y, _point.x - bot.model.body.x) - botAngle;
			var hitPos:Number = hitAngle / Math.PI;
			if (hitPos > 1) hitPos -= 2;
			if (hitPos < -1) hitPos += 2;

			return Math.abs(hitPos);
		}

	}
}